package com.hq.common.utils;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;

/**

 * @since 2015-02-08 17:44
 */
public class SystemHelper {
    //获得系统属性集
    private static Properties sysProperties = System.getProperties();
    //行分页符
    public static String OS_LINE_SEPARATOR = getPropertery("line.separator");
    //文件分隔符号
    public static String OS_FILE_SEPARATOR = getPropertery("file.separator");

    private static String[] localIP;

    public static String getPropertery(String propertyName) {
        return sysProperties.getProperty(propertyName);
    }

    public static String getLocalIpStr() {
        String[] localIP = getLocalIp();
        if (localIP.length == 1) {
            return localIP[0];
        } else {
            return Arrays.asList().toString();
        }
    }

    public static String[] getLocalIp() {
        if (localIP == null || localIP.length == 0) {
            List<String> ips = new ArrayList<String>();
            try {
                String hostAddress;
                Enumeration<?> e1 = NetworkInterface.getNetworkInterfaces();
                while (e1.hasMoreElements()) {
                    NetworkInterface ni = (NetworkInterface) e1.nextElement();
                    Enumeration<?> e2 = ni.getInetAddresses();
                    while (e2.hasMoreElements()) {
                        InetAddress ia = (InetAddress) e2.nextElement();
                        if (ia instanceof Inet6Address)
                            continue;
                        if (!ia.isSiteLocalAddress() && !ia.isLoopbackAddress() && ia.getHostAddress().contains(":")) {
                            continue;
                        }
                        hostAddress = ia.getHostAddress();
                        if ("127.0.0.1".equals(hostAddress) || "localhost".equals(hostAddress)) {
                            continue;
                        }
                        ips.add(hostAddress);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            localIP = new String[ips.size()];
            ips.toArray(localIP);
        }
        return localIP;
    }

    public static String getOSName() {
        return sysProperties.getProperty("os.name");
    }
}
